home *** CD-ROM | disk | FTP | other *** search
- Path: castle.nando.net!news
- From: actuary@nando.net (Bill McCarthy)
- Newsgroups: comp.lang.c
- Subject: Re: why get 9 strings only?
- Date: 25 Jan 1996 03:23:22 GMT
- Organization: News & Observer Public Access
- Message-ID: <4e6t3a$mii@castle.nando.net>
- References: <4e51th$4bi@news.nevada.edu>
- Reply-To: actuary@nando.net (Bill McCarthy)
- NNTP-Posting-Host: 152.52.37.91
- X-Newsreader: IBM NewsReader/2 v1.2
-
- In <4e51th$4bi@news.nevada.edu>,
- chancl@nevada.edu (Clapton Chan) writes:
-
- >I can't figure out why I can only input 9 strings
- >instead of 10 on the following program:
- >
- >**************************************************************
- >
- >/* Write a program that reads a number and then a list of */
- >/* strings (all on separate lines), and then prints one of */
- >/* the lines from the list as selected by the number. */
- >
- >#include <stdio.h>
- >
- >void main()
-
- Make it C. Use int main( void )
-
- >{
- > char str[10][80];
- > int i, j;
- >
- > printf("Enter a number (0-9):\n");
- > scanf("%d", &j);
-
- You're not eating the '\n' and anything typed between the int and
- the '\n'. So, the first gets() is picking up everything after the int
- through the '\n'. I would recommend against using scanf() or gets().
- But if you insist, replace the above scanf() with these two lines:
-
- scanf( "%d%*[^\n]", &j );
- scanf( "%*c" );
-
- > printf("Enter 10 strings:\n");
- > for(i=0; i<10; i++) /* get 10 strings */
- > gets(str[i]); /* but can input 9 strings */
-
- Now you'll be prompted (with no prompt) for 10 strings.
-
- > if(j>0 && j<10)
- > printf("Answer: %s\n", str[j]);
-
- Here's another problem. This will only print the answer if
- j = 1 to 9 inclusive. The valid input of 0 will be skipped. Use:
-
- if ( j >= 0 && j < 10 )
- printf( "Answer: %s", str[j] );
-
- and don't forget to add:
-
- return 0;
-
- >}
-
- Bill McCarthy
- actuary@nando.net
- Wendell, NC USA
-
-